package com.dagene.weixin.web;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.dagene.weixin.service.CoreService;

/**
 * Created with IntelliJ IDEA.
 * User: dingjm
 * Date: 14-1-13
 * Time: 上午10:49
 * To change this template use File | Settings | File Templates.
 */
//http://blog.csdn.net/lyq8479/article/details/9841371

@Controller
@RequestMapping(value = "confirm")
public class InterfaceConfirmController {
    //private static Logger logger = LoggerFactory.getLogger(InterfaceConfirmController.class);
	@Autowired
	CoreService coreService;
    @RequestMapping(method = RequestMethod.GET)
    public void confirm(String signature,String timestamp,String nonce, String echostr,
                          HttpServletRequest request,HttpServletResponse response) {
    	System.out.println(timestamp);
    	
        String token = "123qweasd";    //你自己填写的token
        //对请求参数和自己的token进行排序，并连接排序后的结果为一个字符串
        String[] strSet = new String[]{token, timestamp, nonce};
        java.util.Arrays.sort(strSet);
        String total = "";
        for (String string : strSet) {
            total = total + string;
        }
        //SHA-1加密实例
        MessageDigest sha1 = null;
        try {
            sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(total.getBytes());
            byte[] codedBytes = sha1.digest();
            String codedString = new BigInteger(1, codedBytes).toString(16);//将加密后的字节数组转换成字符串。参见http://hi.baidu.com/aotori/item/c94813c4f15caa60f6c95d4a
            if (codedString.equals(signature)) { //将加密的结果与请求参数中的signature比对，如果相同，原样返回echostr参数内容
                OutputStream os = response.getOutputStream();
                BufferedWriter resBr = new BufferedWriter(new OutputStreamWriter(os));
                resBr.write(echostr);
                resBr.flush();
                resBr.close();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
        }
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request,HttpServletResponse response) {
    	String respMessage = coreService.processRequest(request);  
        
        // 响应消息  
        PrintWriter out=null;
		try {
			out = response.getWriter();
			out.print(respMessage);  
	        
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out.close();  
		}
        
    }

}
